<?php
/**
 * User: onwer
 * Date: 11-11-1
 * Time: 下午11:21
 */
/**
 * 创建表（表名，描述, 类型）
删除表（表名）
选择表（表名）--返回数组
 */
require_once dirname(__FILE__) . '/DB.php';

class Table extends DB
{

    public function __construct()
    {
        parent::__construct('f_system_table');
    }

    /**
     * 创建表
     * @param  string $name    表名
     * @param  string $desc    表描述
     * @param  int $type    表类型  1系统，0用户
     * @return bool
     */

    public function add($name, $desc, $type = 1)
    {

        if (!$this->isletter($name)) {
            $this->errorinfo[2] = '请使用英文名称！';
            return false;
        }
        if (!preg_match('/^0|1$/', $type)) {
            $this->errorinfo[2] = 'type只能为1或0！';
            return false;
        }
        $tablename = $this->table_type[$type] . $name;
        $this->pdo->beginTransaction();
        //在管理表中添加字段
        $r1 = $this->insert(array('table_name' => $tablename, 'table_desc' => $desc, 'table_type' => $type));

        //创建表
        $sql = sprintf('CREATE TABLE  `%s` (
                        `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                        `cat_id` INT( 10 ) NOT NULL,
                        `sys_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                        ) ENGINE = INNODB;',
            $tablename);
        $r2 = $this->exec($sql);

        return $this->endTranst($r1,$r2);
    }

    /**
     * @param string  $tid    表名
     * @return bool
     */
    public function del($tid)
    {

        $curtabelarr = $this->queryid($tid);

        if (empty($curtabelarr)) {
            $this->errorinfo[2] = '该表已经删除了！';
            return false;
        }
        $curtabel = $curtabelarr[0];
        //开始事务
        $this->pdo->beginTransaction();
        //从管理字段表中删除字段
        $sql = sprintf('DELETE FROM `f_system_filed` WHERE `f_system_filed`.`table_id` = %d ', $tid);
        $r1 = $this->exec($sql);
        //从管理表中删除表
        $r2 = $this->delete(sprintf('id=%d', $tid));
        //删除表
        $sql = sprintf('DROP TABLE %s', $curtabel['table_name']);
        $r3 = $this->exec($sql);

        return $this->endTranst($r1,$r2,$r3);

    }

    public function queryid($id)
    {
        return $this->select(sprintf('id=%d', $id));
    }


}
